package main

import (
	"os"

	app "gitee.com/fanshuaiself/sidecar/cmd/app"
	"gitee.com/fanshuaiself/sidecar/nacos"
	proxy "gitee.com/fanshuaiself/sidecar/plugin/proxy"
	register "gitee.com/fanshuaiself/sidecar/plugin/register"
	web "gitee.com/fanshuaiself/sidecar/plugin/web"
	util "gitee.com/fanshuaiself/sidecar/util"
	log "github.com/sirupsen/logrus"
)

func main() {
	log.Println("starting sidecar...")

	config := buildConfig()
	plugins := loadPlugin()

	
	nacos.Init(config.NacosServer, config.NacosServiceName, config.NacosServiceGroup)
	app := app.NewApp(config, plugins)
	err := app.Start()
	if err != nil {
		log.Fatal(err)
	}
}


func buildConfig() *util.Config {
	config := new(util.Config)
	nacosServer, ok := os.LookupEnv("MESH_APP")
	if !ok {
		log.Fatal("cannot find MESH_APP")
	}
	nacosServiceName, ok := os.LookupEnv("NACOS_DISCOVERY_SERVER_ADDR")
	if !ok {
		log.Fatal("cannot find NACOS_DISCOVERY_SERVER_ADDR")
	}
	nacosServiceGroup, ok := os.LookupEnv("SPRING_CLOUD_NACOS_DISCOVERY_METADATA_GROUP")
	if !ok {
		log.Fatal("cannot find SPRING_CLOUD_NACOS_DISCOVERY_METADATA_GROUP")
	}

	config.UseFasthttp = false
	config.NacosServer = nacosServer
	config.NacosServiceName = nacosServiceName
	config.NacosServiceGroup = nacosServiceGroup
	config.HeartBeatInterval = 5
	config.Host = "http://127.0.0.1:8080"
	return config
}

func loadPlugin() []app.Plugin {
	plugins := []app.Plugin{
		&web.WebPlugin{}, 
		&register.RegisterPlugin{},
		&proxy.ProxyPlugin{},
	}
	return plugins
}